﻿using System;
using System.Diagnostics;
using System.Threading;
using System.Web;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;

using YouHP.Config;
using YouHP.Utility;

namespace YouHP.HttpModule
{
    /// <summary>
    /// rewrite url 类
    /// </summary>
    public class RewriterUrlModule : System.Web.IHttpModule
    {
        /// <summary>
        /// 实现接口的Init方法
        /// </summary>
        /// <param name="context"></param>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(RewriteUrlForRequest);
        }

        public void Application_OnError(Object sender, EventArgs e)
        {
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            //if (context.Server.GetLastError().GetBaseException() is MyException)
            {
                //MyException ex = (MyException) context.Server.GetLastError().GetBaseException();
                context.Response.Write("<html><body style=\"font-size:14px;\">");
                context.Response.Write("网页打开错误！<br />");
                context.Response.Write("<textarea name=\"errormessage\" style=\"width:80%; height:200px; word-break:break-all\">");
                context.Response.Write(System.Web.HttpUtility.HtmlEncode(context.Server.GetLastError().ToString()));
                context.Response.Write("</textarea>");
                context.Response.Write("</body></html>");
                context.Response.End();
            }
        }

        /// <summary>
        /// 实现接口的Dispose方法
        /// </summary>
        public void Dispose()
        {
        }


        /// <summary>
        /// 重写Url
        /// </summary>
        /// <param name="sender">事件的源</param>
        /// <param name="e">包含事件数据的 EventArgs</param>
        private void RewriteUrlForRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication)sender).Context;
            string requestPath = context.Request.Path.ToLower();
            string newUrl = "";

            if (requestPath.StartsWith("/index.aspx"))
            {
                context.RewritePath(BaseConfig.Instance.WebRealPath + requestPath, string.Empty, "");
            }
            else if (requestPath.StartsWith("/tools"))
            {
                //context.RewritePath(BaseConfig.Instance.WebRealPath + requestPath, string.Empty, "");
            }
            else if (requestPath.StartsWith("/support"))    //对于资源路径不处理
            {
                //context.RewritePath(BaseConfig.Instance.WebRealPath + requestPath, string.Empty, "");
            }
            else if (requestPath.StartsWith("/admin"))    //对于资源路径不处理
            {
                //context.RewritePath(BaseConfig.Instance.WebRealPath + requestPath, string.Empty, "");
            }
            else  
            {
                foreach (URLRewrite url in SiteUrls.GetSiteUrls().Urls)
                {
                    if (url.Pattern.Length <= 0)    //没有匹配模式，直接指定页面的情况
                    {
                        if (url.Path.Equals(requestPath, StringComparison.CurrentCultureIgnoreCase))
                        {
                            newUrl = url.Page;
                            context.RewritePath(BaseConfig.Instance.WebRealPath + newUrl);
                            return;
                        }
                    }
                    else if (Regex.IsMatch(requestPath, url.Pattern, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase))
                    {
                        newUrl = Regex.Replace(requestPath, url.Pattern, url.QueryString, Utils.GetRegexCompiledOptions() | RegexOptions.IgnoreCase);
                        context.RewritePath(BaseConfig.Instance.WebRealPath + newUrl);
                        return;
                    }
                }
            }            
        }
    }
}
